<template>
  <div>
    <el-table
      ref="roles"
      :data="roles"
      :show-header="false"
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column
        prop="name"
      />
      <el-table-column
        width="70"
      >
        <template slot-scope="scope">
          <span>
            <el-button
              type="primary"
              circle
              style="padding:3px;"
              title="编辑角色"
              size="mini"
              @click="() => handleEdit(scope.row)"
            >
              <svg-icon icon-class="edit" />
            </el-button>
          </span>
          <span>
            <el-button
              v-if="scope.row.id !== 'admin'"
              type="danger"
              circle
              style="padding:3px;"
              title="删除角色"
              size="mini"
              @click="() => handleDelete(scope.row)"
            >
              <svg-icon icon-class="delete" />
            </el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <edit-role ref="editRole" :fn-edit="fnEdit" @edit="handleOnRoleEdit" />
    <delete-role ref="deleteRole" :fn-delete="fnDelete" @delete="handleOnRoleDelete" />
  </div>
</template>

<script>
import EditRole from './EditRole'
import DeleteRole from './DeleteRole'

export default {
  name: 'RoleList',
  components: { EditRole, DeleteRole },
  props: {
    roles: {
      type: Array,
      default() {
        return []
      }
    },
    fnEdit: { type: Function, required: true },
    fnDelete: { type: Function, required: true }
  },
  watch: {
    'roles': {
      immediate: true,
      deep: true,
      handler: function() {
        if (this.roles && this.roles.length > 0) {
          this.$refs.roles.setCurrentRow(this.roles[0])
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.roles && this.roles.length > 0) {
        this.$refs.roles.setCurrentRow(this.roles[0])
      }
    })
  },
  methods: {
    setCurrent(cur) {
      this.$refs.roles.setCurrentRow(cur)
    },
    handleOnRoleDelete(role) {
      this.roles.forEach((item, index) => {
        if (item['id'] === role['id']) {
          this.roles.splice(index, 1)
        }
      })
    },
    handleOnRoleEdit(role) {
      this.roles.forEach(item => {
        if (item['id'] === role['id']) {
          item['name'] = role['name']
        }
      })
    },
    handleEdit(data) {
      this.$refs.editRole.show(data)
    },
    handleDelete(data) {
      this.$refs.deleteRole.show(data)
    },
    handleCurrentChange(row) {
      if (row) {
        this.$emit('onChange', row)
      }
    }
  }
}
</script>
